//index.js
//获取应用实例
const app = getApp()

var http = require('../../utils/http.js');

Page({
  data: {
    userId: wx.getStorageSync('userId'),
    userInfo: {
      avatar: '/images/user-none.png',
      nickname: '请登录'
    },
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.getUser();
    }
  },
  onLogin: function () {
    wx.getUserInfo({
      success: res => {
        // 更新用户信息
        var params = {
          url: "/userApi",
          method: "POST",
          data:{
            id: wx.getStorageSync('userId'),
            nickname: res.userInfo.nickName,
            avatar: res.userInfo.avatarUrl
          }
        };
        http.request(params);
        this.getUser();
      }
    })
  },
  getUser: function(){
    var ths = this
    var params = {
      url: "/userApi/"+this.data.userId,
      method: "GET",
      callBack: function (res) {
        ths.setData({
          userInfo: res.data,
          hasUserInfo: true
        });
      }
    };
    http.request(params);
  },
  /**
   * 页面跳转
  */
  goPages: function (e) {
    if (this.data.hasUserInfo) {
      wx.navigateTo({
        url: e.currentTarget.dataset.url
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
})
